package top.csy8888.likework.common.confirm;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * @author CSY
 * @date 2025 - 10 - 15
 */
@Component
@RequiredArgsConstructor
public class RabbitManager<T> {
    private final RabbitTemplate rabbitTemplate;

    public void send(String exchange, String routingKey, String callbackBeanName, T data){
        try{
            //创建CorrelationData对象并设置一个id
            CorrelationData cdata = new CorrelationData(UUID.randomUUID().toString());
            //将数据转换为byte数组
            byte[] bytes = new ObjectMapper().writeValueAsBytes(data);
            //创建Message对象,并将byte数组传入
            Message message = new Message(bytes);
            //创建ReturnedMessage,投递失败返回的消息对象
            ReturnedMessage returnedMessage = new ReturnedMessage(message,0,callbackBeanName,exchange,routingKey);
            //将ReturnedMessage保存到cdata中
            cdata.setReturned(returnedMessage);
            //执行发送
            rabbitTemplate.convertAndSend(exchange,routingKey,data,cdata);
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
}
